package writeor.aidraw.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import writeor.aidraw.model.AiImages;
import writeor.aidraw.model.Generate_Post;
import writeor.aidraw.model.User;
import writeor.aidraw.service.GenerateService;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;

@Controller
public class GenerateController {
    @Autowired
    private GenerateService generateService;
    @GetMapping(value = "/generate")
    public  String home(Model model){
        Generate_Post generate_post=new Generate_Post();
        //给网页传入默认值
        generate_post.setWidth("512");
        generate_post.setHeight("768");
        generate_post.setScale("12");
        generate_post.setSampler("k_euler_ancestral");
        generate_post.setSteps("24");
        generate_post.setN_samples("1");
        generate_post.setUcPreset("0");
        generate_post.setUc("lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry, lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry");
        //图片的三个选项
        generate_post.setImage(null);
        generate_post.setStrength("0.7");
        generate_post.setNoise("0.2");
        model.addAttribute("generate_post",generate_post);
        //System.out.print("传入generate_pos="+generate_post);

        return "generate";
    }


    @PostMapping("/generate")
    public  String generate(Generate_Post generate_post, HttpServletRequest request, HttpSession session)throws FileNotFoundException {
        //generate_post.toString();
//        User user= (User) session.getAttribute("USER_SESSION");
//        System.out.println("用户名为:"+user.getUser_name());
        //判断seed是否为空，为空传到生成服务器会报错
        if(generate_post.getSeed().isBlank()){
            System.out.println("将seed置null");
            generate_post.setSeed(null);
        }
        //System.out.println( "图片："+generate_post.getImage());

        //判断是否有图片
        if (!generate_post.getImage().isEmpty()) {
            // 设置上传文件的保存地址目录
            String dirPath = request.getServletContext().getRealPath("/public/");
            File filePath = new File(dirPath);
            System.out.println("=========dirPath=" + dirPath);
            // 如果保存文件的地址不存在，就先创建目录
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            // 获取上传文件的原始名称
            String originalFilename = generate_post.getImage().getOriginalFilename();
            //String classpath = ResourceUtils.getURL("classpath:static").getPath();

            try {
                // 使用MultipartFile接口的方法完成文件上传到指定位置
                generate_post.getImage().transferTo(new File( dirPath+originalFilename));
                //C:\Users\Administrator\AppData\Local\Temp\tomcat-docbase.8080.1523113124524655072\public\
                request.setAttribute("fileurl", dirPath+originalFilename);
                System.out.println(dirPath+originalFilename);

            } catch (Exception e) {
                e.printStackTrace();

            }

        }else{//没有图片，将图片专有的三个选项置空
            System.out.println("没有图片，将图片专有的三个选项置空");
            generate_post.setImage(null);
            generate_post.setNoise(null);
            generate_post.setStrength(null);
        }

        //System.out.print("okkkkkkkkkkkk~~~~"+generate_post.toString());
        try{
            //向生成服务器发送post请求
            //获取RestTemplate对象
            RestTemplate restTemplate = new RestTemplate();
//        设置请求头，请求类型为json
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
//        设置请求参数
            HashMap<String, String> map = new HashMap<>();
            //入参
            map.put("prompt",generate_post.getPrompt());
            map.put("width", generate_post.getWidth());
            map.put("height", generate_post.getHeight());
            map.put("scale", generate_post.getScale());
            map.put("sampler", generate_post.getSampler());
            map.put("steps", generate_post.getSteps());
            map.put("seed",generate_post.getSeed());
            map.put("n_samples", generate_post.getN_samples());
            map.put("ucPreset", generate_post.getUcPreset());
            map.put("uc",generate_post.getUc());
            //上传图片的三个选项

            if(request.getAttribute("fileurl")!=null){//如果有图片
                //读入图片
                String path = (String) request.getAttribute("fileurl");

                File sourceimage = new File(path);
                BufferedImage image = ImageIO.read(sourceimage);
                String string_img = imgToBase64String(image);
                System.out.println("图片数据"+string_img);
                map.put("strength", "0.7");
                map.put("noise", "0.2");
                map.put("image", string_img);
            }


            //用HttpEntity封装整个请求报文
            HttpEntity<HashMap<String, String>> request2 = new HttpEntity<>(map, headers);
//        开始调用
//        参数1：目标请求地址
//        参数2：请求体
//        参数3：目标请求接口的返回值类型（execute接口的返回值类型）
            String response = restTemplate.postForObject("http://127.0.0.1:6969/generate-stream", request2, String.class);
            System.out.println("回复为"+response);
            //解析传回的json
            JSONObject jsonObject1 = JSONObject.parseObject(response);
            //System.out.print("传回数据为:"+jsonObject1.toString());
            System.out.println("种子："+jsonObject1.get("seed"));
            //获取存在sesson里的用户信息
            User user= (User) session.getAttribute("USER_SESSION");

            String prompt=jsonObject1.get("prompt").toString();
            String seed=jsonObject1.get("seed").toString();
            String author=user.getUser_name();

            //model.addAttribute(jsonObject1);
            //跳转到图片详情页面//detail里面本来用的是aiimage类，有些参数没有，不能用post类，
            //组成一个aiimages类返回到detail页面和合成服务
            AiImages aiImages=new AiImages();
            if(prompt==""){//没有标签的时候，存入数据库不能加空格，不然页面读取不了
                aiImages.setImg_path("s-"+seed+".png");
            }else{
                if(prompt.length()>128){//因为windows系统里只能存入 128 加sedd.png长度的文件名，多的要剪掉
                    aiImages.setImg_path(prompt.substring(0,128)+" "+"s-"+seed+".png");
                }else {
                    aiImages.setImg_path(prompt+" "+"s-"+seed+".png");
                }

            }

            aiImages.setAuthor(author);
            aiImages.setLike(0);
            aiImages.setPrompt(prompt);//经过py服务器处理过的prompt
            aiImages.setWidth(generate_post.getWidth());
            aiImages.setHeight(generate_post.getHeight());
            aiImages.setSteps(generate_post.getSteps());
            aiImages.setScale(generate_post.getScale());
            aiImages.setSampler(generate_post.getSampler());
            aiImages.setSeed(seed);
            aiImages.setN_samples(generate_post.getN_samples());
            aiImages.setStrength(generate_post.getStrength());
            aiImages.setNoise(generate_post.getNoise());
            aiImages.setUc(generate_post.getUc());
            //存入 给detail页面用
            //model.addAttribute("image_info",aiImages);
            //model.addAttribute("img_path",aiImages.getImg_path());
            request.setAttribute("image_info",aiImages);
            request.setAttribute("img_path",aiImages.getImg_path());
            //存入用户和图片信息
            //因为文件名在window里的长度有限，不能超出限制
            int row = generateService.GenerateImg(aiImages);
            if(row>0){
                System.out.println("存入用户和图片信息成功。");
            }
            //return "Image_detail";

            //attr.addAttribute("image_path", aiImages.getImg_path());//跳转地址带上test参数
            //String url = "/ImageDetail?img_path="+"d";
            Thread.sleep(2000);

            //return "forward:/ImageDetail?img_path="+aiImages.getImg_path();
            return "redirect:/ImageDetail?img_path="+aiImages.getImg_path();

        } catch (Exception e) {
            System.out.println("连接生成服务器失败或参数错误。");
            throw new RuntimeException(e);
        }


    }

    //把图片转换成string类型
    public static String imgToBase64String(final RenderedImage img) {
        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(img, "png", Base64.getEncoder().wrap(os));
            return os.toString(StandardCharsets.ISO_8859_1.name());
        } catch (final IOException ioe) {
            throw new UncheckedIOException(ioe);
        }
    }
    //把string类型转换成图片
//    public static BufferedImage base64StringToImg(final String base64String) {
//        try {
//            BASE64Decoder decoder = new BASE64Decoder();
//            byte[] bytes = decoder.decodeBuffer(base64String);
//            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
//            return ImageIO.read(bais);
//        } catch (final IOException ioe) {
//            throw new UncheckedIOException(ioe);
//        }
//    }

}
